import { apiUrl } from '@/configs'
import { useUserStore } from '@/stores/user'

const extension = ['.doc', '.docx']

export function useResumeAttachment() {
	const { getUserInfo } = useUserStore()

	const chooseAttachment = () => {
		// #ifdef H5
		uni.chooseFile({
		  count: 1,
		  extension,
		  success: (chooseFileRes) => {
		    uni.showLoading({ mask: true })
		    const tempFilePaths = chooseFileRes.tempFilePaths

		    uploadAttachment(tempFilePaths[0])
		  },
		})
		// #endif
	  // #ifdef MP-WEIXIN
	  wx.chooseMessageFile({
	    count: 1,
	    extension,
	    success: (chooseFileRes) => {
	      uni.showLoading({ mask: true })
	      const tempFiles = chooseFileRes.tempFiles

	      uploadAttachment(tempFiles[0])
	    },
	  })
	  // #endif
	}

	const uploadAttachment = (filePath: string) => {
	  uni.uploadFile({
	    url: `${apiUrl}/upload/index`,
	    filePath,
	    name: 'file',
	    success: (uploadFileRes) => {
	      try {
	        const ret = JSON.parse(uploadFileRes.data)
	        console.log('上传结果：', ret)
	        if (ret.code === 1) {
	          console.log(ret.data)
	          updateResume(ret.data.url)
	        } else {
	          uni.showToast({ title: '上传附件失败', icon: 'none' })
	          uni.hideLoading()
	        }
	      } catch (e) {
	        uni.showToast({ title: '上传附件失败', icon: 'none' })
	        uni.hideLoading()
	      }
	    },
	    fail: (uploadFileError) => {
	      console.log(uploadFileError)
	      uni.showToast({ title: '上传附件失败', icon: 'none' })
	      uni.hideLoading()
	    },
	  })
	}

	const updateResume = async (attachmentUrl: string) => {
	  try {
	    const myResumeRes = await uni.$u.get('/resume/my')
	    if (myResumeRes.code === 1) {
	      const myResume = myResumeRes.data

	      const data = {
	        nickname: myResume.nickname,
	        gender: myResume.gender,
	        birthday: myResume.birthday,
	        city: myResume.city,
	        work: myResume.work,
	        highest_education: myResume.highest_education,
	        email: myResume.email,
	        avatar: myResume.avatar,
	        resume_status: myResume.resume_status,
	        fijian: attachmentUrl,
	      }
	      const res = await uni.$u.post('/user/profile', data)
	      if (res.code === 1) {
	        getUserInfo()
	      } else {
	        uni.showToast({ title: '更新个人信息失败', icon: 'none' })
	      }
	    } else {
	      uni.showToast({ title: '更新个人信息失败', icon: 'none' })
	    }
	  } catch (e) {
	    uni.showToast({ title: '更新个人信息失败', icon: 'none' })
	  } finally {
	    uni.hideLoading()
	  }
	}

	return {
		chooseAttachment,
	}
}
